import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Run {

	private static final String JJ_NAME = "jpjxlO";
	private File startFile = new File("C:/");
	private Pattern pattern = Pattern
			.compile(".*(archive\\.db|archives\\.dat)$");
	private SimpleDateFormat formatter = new SimpleDateFormat(
			"yyyy-MM-dd-HH-mm-ss");
	private String destNameDate = formatter.format(new Date());
	private int counter = 0;

	private void search(File file) {
		File[] fileList = file.listFiles();
		if (fileList != null) {
			for (File searchFile : fileList) {
				if (searchFile.isDirectory()) {
					search(searchFile);
				} else {
					String path = searchFile.getAbsolutePath();
					Matcher matcher = pattern.matcher(path.toLowerCase());
					if (matcher.matches()) {
						prepareToCoy(path);
					}
				}
			}
		}

	}

	public void invoke() {
		search(startFile);
	}

	private void prepareToCoy(String path) {
		counter++;
		String name = (path.endsWith("b")) ? "Archive.db" : "archives.dat";

		String destName = JJ_NAME + "/" + destNameDate + "/" + counter;
		new File(destName).mkdirs();
		copy(path, destName + "/" + name);
	}

	private void copy(String srFile, String dtFile) {
		try {
			File source = new File(srFile);
			File destination = new File(dtFile);
			InputStream in = new FileInputStream(source);

			// For Append the file.
			// OutputStream out = new FileOutputStream(f2,true);

			// For Overwrite the file.
			OutputStream out = new FileOutputStream(destination);

			byte[] buf = new byte[1024];
			int len;
			while ((len = in.read(buf)) > 0) {
				out.write(buf, 0, len);
			}
			in.close();
			out.close();
		} catch (Exception ex) {
		}
	}

	public static void main(String args[]) {
		boolean exists = new File(JJ_NAME).exists();
		if (!exists) {
			System.exit(0);
		}
		Date startTime = new Date();
		new Run().invoke();
		Date endTime = new Date();

		// System.out.println((endTime.getTime() - startTime.getTime()) / 1000.0
		// + "s");
	}
}